package us.nchu.tomtiger.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import us.nchu.tomtiger.utils.EncryptUtil;
import us.nchu.tomtiger.utils.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by XiongXuan on 2018/1/8.
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 判断访问方式的是get（访问页面）还是post（登录）还是delete（登出）
        if (httpServletRequest.getMethod().equals("GET"))
            return preGet(httpServletRequest, httpServletResponse);
        else if (httpServletRequest.getMethod().equals("POST"))
            return prePost(httpServletRequest);
        else
            return preDelete(httpServletRequest);
    }

    private boolean preDelete(HttpServletRequest httpServletRequest) {
        String user = (String) httpServletRequest.getSession().getAttribute("user");
        return user == null;
    }

    private boolean preGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        // 判断用户是否已经登录，如果已经登录，则跳转到个人中心界面
        if (UserUtil.isLogin(httpServletRequest)) {
            httpServletResponse.sendRedirect("/center");
            return false;
        }
        return true;
    }

    private boolean prePost(HttpServletRequest httpServletRequest) {
        // 获取传入的参数
        String phoneNumber = httpServletRequest.getParameter("phoneNumber");
        String password = httpServletRequest.getParameter("password");
        String sha1_result = httpServletRequest.getParameter("sha1_result");
        String timestamp = httpServletRequest.getParameter("timestamp");

        if (phoneNumber == null || password == null || sha1_result == null || timestamp == null) {
            return false;
        }

        if (!UserUtil.checkTime(timestamp)) {
            return false;
        }

        return sha1_result.equals(EncryptUtil.getSha1(password + phoneNumber + timestamp));
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
